package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/add")
    public User add(User user) {
        return user;
    }

    @RequestMapping("/name")
    public String name(@RequestParam(value="n",required = false) String name) {
        return name;
    }

    /**
     * 获取前端的 JSON 对象
     */
    @RequestMapping("/add_json")
    public User addByJson(@RequestBody User user) {
        return user;
    }

    @RequestMapping("/detail/{aid}")
    public Integer detail(@PathVariable("aid") Integer aid) {
        return aid;
    }

    @RequestMapping("/detail2/{aid}/{name}")
    public String detail2(@PathVariable("aid") Integer aid, @PathVariable("name") String name) {
        return "aid:"+aid+" name:"+name;
    }

    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
        // 1.生成一个唯一的 id | UUID = 全球唯一 ID -> MAC + 随机种子 + 加密算法
        String name = UUID.randomUUID().toString().replace("-","");
        // 2.得到源文件的后缀名
        name += (file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        String path = "F:\\image\\"+name;
        // 保存文件
        file.transferTo(new File(path));
        return path;
    }

    /**
     * 获取 Cookie
     */
    @RequestMapping("/getcookie")
    public String getCookie(@CookieValue(value="java", required = false) String ck) {
        return ck;
    }

    private static String _SESSION_KEY = "SESSION_KEY";

    @RequestMapping("/set_sess")
    public String setSess(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session != null) {
            session.setAttribute(_SESSION_KEY, "张三");
            return "session set success";
        }else {
            return "session set fail";
        }
    }
    /**
     * 获取 session
     */
    @RequestMapping("/get_sess")
    public String getSess(@SessionAttribute(required = false,value = "SESSION_KEY") String name) {
        return name;
    }

    @RequestMapping("/header")
    @ResponseBody
    public String header(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent："+userAgent;
    }
}
